<template>
  <div class="namelist-box">
    <div style="margin-bottom: 16px">
      <a-button type="primary" @click="openPop('add')">
        添加分类
      </a-button>
    </div>
    <a-table :columns="columns" :data-source="data" :loading="tableLoading" :pagination="false">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <span class="table-operation">
            <a-button type="link" @click="openPop('change', record)">修改</a-button>
            <a-button type="link" danger @click="delCategory(record.key)">删除</a-button>
            <a-button type="link" @click="openPop('add', { pid: record.key })" v-if="record.level < 3">添加子分类</a-button>
          </span>
        </template>
      </template>
    </a-table>
    <a-modal v-model:open="showAction" :title="userItem ? '修改分类' : ' 添加分类'" @cancel="handleCancel(true)"
      :maskClosable="false">
      <a-form :model="form" name="basic" class="login-form" autocomplete="off" @finish="handleSubmit">
        <a-form-item label="名称" name="name" :rules="[{ required: true, message: '请输入分类名称' }]">
          <a-input v-model:value="form.name" />
        </a-form-item>
        <a-form-item label="备注" name="desc">
          <a-input v-model:value="form.desc" />
        </a-form-item>
        <a-form-item label="权重" name="weight">
          <div style="display: flex;align-items: center;">
            <a-input-number id="inputNumber" v-model:value="form.weight" :min="0" :max="99" /><span
              style="margin-left: 20px;">请输入0~99的数字</span>
          </div>
        </a-form-item>
        <a-form-item label="分类图片" name="img">
          <div class="upload-box">
            <div class="up-img" v-if="form.img">
              <a-image :src="form.img" width="240px" height="100px" alt="main-img" />
              <close-circle-outlined class="close-icon" @click="delImg('img')" />
            </div>
            <a-upload v-else name="avatar" list-type="picture-card" class="avatar-uploader" :customRequest="upFile"
              :show-upload-list="false">
              <div>
                <loading-outlined v-if="fileLoading"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">Upload</div>
              </div>
            </a-upload>
          </div>
        </a-form-item>
        <a-button type="primary" html-type="submit" :loading="loading">提交</a-button>
      </a-form>
      <template #footer>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import * as Api from "@req/api";
import { suc, upImgFun } from "../../utils";
import { Modal, message } from "ant-design-vue";
import { LoadingOutlined, PlusOutlined, CloseCircleOutlined } from '@ant-design/icons-vue';
const columns = [
  {
    title: "分类名称",
    dataIndex: "name",
    width: 400
  },
  {
    title: "排序权重",
    dataIndex: "weight",
  },
  { title: "操作", dataIndex: "action", key: "action" },
];

const data = ref([]);
const loading = ref(false);
const showAction = ref(false);
const userItem = ref(null)
const tableLoading = ref(false);
const fileLoading = ref(false)
const form = ref({
  name: null,
  desc: null,
  img: null,
  weight: 0,
  parent_id: null
});

const upFile = async (file) => {
  fileLoading.value = true;
  form.value.img = await upImgFun(file)
  fileLoading.value = false;
}

const handleCancel = () => {
  showAction.value = false;
  form.value = {
    name: null,
    desc: null,
    img: null,
    weight: 0,
    parent_id: null
  }
}

onMounted(() => {
  getCategoryList()
});

const getCategoryList = () => {
  tableLoading.value = true;
  Api.getCategoryList().then((res) => {
    if (suc(res.status)) {
      data.value = handleList(res.data, 1);
    }
    tableLoading.value = false;
  });
}


const handleList = (list, level, pid) => {
  if (!list && list.length <= 0) return;
  for (const item of list) {
    if (pid) item.pid = pid;
    item.level = level;
    if (item.children.length <= 0) {
      delete item.children
    } else if (item.children) {
      item.children = handleList(item.children, level + 1, item.key);
    }
  }
  return list;
}

const openPop = (type, item) => {
  if (type != 'add') {
    userItem.value = item;
  }
  if (item) {
    form.value.name = item.name;
    form.value.desc = item.desc;
    form.value.img = item.img;
    form.value.weight = item.weight;
    form.value.parent_id = item.pid;
    console.log(form.value)
  }
  showAction.value = true;
}
const delCategory = (id) => {
  Modal.confirm({
    title: "确认删除吗？",
    content: "删除后不可恢复，需重新添加",
    okText: "确认",
    cancelText: "取消",
    onOk() {
      Api.delCategory(id).then((res) => {
        if (suc(res.status)) {
          message.success(res.message)
          getCategoryList()
        }
      })
    },
  });
}

const handleSubmit = () => {
  loading.value = true;
  if (userItem.value) {
    changeCategory()
  } else {
    submit()
  }
}

const submit = () => {
  Api.addCategory(form.value).then((res) => {
    loading.value = false;
    if (suc(res.status)) {
      message.success(res.message)
      handleCancel()
      getCategoryList()
    }
  })
}

const changeCategory = () => {
  Api.changeCategory(userItem.value.key, form.value).then((res) => {
    loading.value = false;
    if (suc(res.status)) {
      message.success(res.message)
      handleCancel()
      getCategoryList()
    }
  })
}

</script>

<style lang="postcss" scoped>
.namelist-box {
  padding: 16px;
}

::v-deep .ant-table-row-level-1 {
  background-color: rgba(0, 0, 0, 0.03);
}

.login-form {
  padding: 30px 30px 0;

  .ant-btn {
    display: block;
    margin-left: auto;
  }

  ::v-deep .ant-form-item-label>label {
    justify-content: end;
    width: 70px;
  }

  .upload-box {
    ::v-deep .ant-upload {
      overflow: hidden;
      width: 240px;
      height: 100px;
      box-sizing: border-box;

      &.ant-upload-select {
        width: 240px;
        height: 100px;
        box-sizing: border-box;
      }
    }
  }

  .up-img {
    position: relative;
    width: 240px;
    height: 100px;

    &.list {
      width: 100px;
      height: 100px;
    }

    ::v-deep .ant-image {
      border-radius: 10px;
      overflow: hidden;

      .ant-image-img {
        object-fit: cover;
      }
    }

    .close-icon {
      position: absolute;
      z-index: 1;
      font-size: 25px;
      right: -10px;
      top: -10px;
      cursor: pointer;
    }
  }
}
</style>